package com.lecture.springlecture.util;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.KieScanner;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class KieSessionFactory {

    private static final String RULES_PATH = "rules/";
    private static KieContainer kieContainer;
    private static KieScanner kieScanner;
    private static KieSession kieSession;

    public static synchronized KieSession getKieSession() {
        if (kieSession == null) {
            KieRepository repository = KieServices.Factory.get().getRepository();
            repository.addKieModule(repository::getDefaultReleaseId);
            KieBuilder kieBuilder = KieServices.Factory.get().newKieBuilder(getKieFileSystem());
            kieBuilder.buildAll();
            kieContainer = KieServices.Factory.get().newKieContainer(repository.getDefaultReleaseId());
            kieScanner = KieServices.Factory.get().newKieScanner(kieContainer);
            kieScanner.start(10000L); // 每隔10秒扫描并加载新规则
            kieSession = kieContainer.newKieSession();








        }
        return kieSession;
    }

    public static KieFileSystem getKieFileSystem() {
        KieFileSystem kieFileSystem = KieServices.Factory.get().newKieFileSystem();
        for (Resource ruleFile : getRuleFiles()) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + ruleFile.getFilename(),"UTF-8"));
        }
        return kieFileSystem;
    }

    //获取规则文件
    private static Resource[] getRuleFiles() {
        Resource[] resources = new Resource[0];
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            resources = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resources;
    }

    public static void triggerRulesScan() {
        kieScanner.scanNow();
    }
}
